<?php

namespace App\Http\Controllers;

use App\Exceptions\AuthException;
use App\Exceptions\FobbidenException;
use App\Models\UserModel;
use App\Services\BlacklistService;
use App\Services\UserService;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * 用户列表
     *
     * @param Request $request
     * @param UserService $userService
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, UserService $userService)
    {
        if (auth()->user() && auth()->user()->role != UserModel::ROLE_ADMIN) {
            return redirect('/feedback');
        }

        $page = $request->input('page', 1);
        $page_size = $request->input('page_size', 0);

        $count = $userService->countUsers();
        $data = $userService->getPaginatedUsers($page_size)
            ->appends(['page' => $page]);

        return view('user.index', ['data' => $data, 'count' => $count]);
    }

    /**
     * 加入黑名单
     *
     * @param BlacklistService $blacklistService
     * @param int $user_id
     * @return array|void
     */
    public function block(BlacklistService $blacklistService, int $user_id)
    {
        try {
            $res = $blacklistService->blockUser($user_id);
            if (! $res) {
                return $this->error('更新失败');
            }
        } catch (AuthException|FobbidenException $e) {
            return $this->error($e->getMessage(), $e->getCode());
        } catch (\Exception $e) {
            return $this->error('更新失败，请重试');
        }
    }
}
